package java2022spring;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.math.BigInteger;
import java.math.BigDecimal;

public class Calculator implements ActionListener {

    private JFrame frame = new JFrame();

    private String[] keys = {"%", "CE", "C", "←", "n!", "aⁿ", "cos", "sin", "1⁄x", "x²", "√x", "÷", "7", "8", "9",
            "×", "4", "5", "6", "－", "1", "2", "3", "+", "+/-", "0", ".", "="};
    private JButton button[] = new JButton[keys.length]; 
    private JTextField resultText = new JTextField("0");
    private JTextField processText = new JTextField();
    private boolean firstDigit = true;  
    private double resultNum = 0.0000;   
    private String operator = "=";  
    private boolean operateValidFlag = true;   

    char charA;

    public Calculator() {
        init();  

        frame.setTitle("计算器");
        frame.setSize(350, 550);
        frame.setLocation(500, 300);
        frame.setResizable(true);  
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


    private void init() {
        Color color1 = new Color(181, 181, 181);
        Color color2 = new Color(126, 192, 238);  
        Color color3 = new Color(232, 232, 232);  

        JPanel resultTextPanel = new JPanel();
        resultTextPanel.setLayout(new BorderLayout());
        resultTextPanel.setSize(400, 50);
        resultTextPanel.add(resultText);
        resultText.setFont(new Font("黑体", Font.BOLD, 55));
        resultText.setHorizontalAlignment(JTextField.RIGHT); 
        resultText.setEditable(false);  
        resultText.setBorder(null); 
        resultText.setBackground(color1);

        JPanel processTextPanel = new JPanel();
        processTextPanel.setLayout(new BorderLayout());
        processTextPanel.setSize(400, 50);
        processTextPanel.add(processText);
        processText.setFont(new Font("黑体", Font.PLAIN, 25));  
        processText.setHorizontalAlignment(JTextField.RIGHT);  
        processText.setEditable(false);  
        processText.setBorder(null);  

        processText.setBackground(color1);

        JPanel keysPanel = new JPanel();
        keysPanel.setLayout(new GridLayout(7, 4, 2, 2));

        for (int i = 0; i < 12; i++) {
            button[i] = new JButton(keys[i]);
            Dimension preferredSize = new Dimension(95, 50);
            button[i].setPreferredSize(preferredSize);
            keysPanel.add(button[i]);
            button[i].setBackground(color3);
            button[i].setForeground(Color.black);
            button[i].setFont(new Font(Font.SERIF, Font.PLAIN, 18));
            if (i == 11 || i == 3) button[i].setFont(new Font(Font.SERIF, Font.PLAIN, 30));
            if (i == 1 || i == 2) button[i].setFont(new Font("黑体", Font.PLAIN, 18));
            button[i].setBorderPainted(false);  
        }

        for (int i = 12; i < keys.length; i++) {
            button[i] = new JButton(keys[i]);
            Dimension preferredSize = new Dimension(95, 50);
            button[i].setPreferredSize(preferredSize);
            keysPanel.add(button[i]);
            if ((i + 1) % 4 == 0) {
                button[i].setBackground(color3);
                button[i].setFont(new Font(Font.SERIF, Font.PLAIN, 30));
            } else {
                button[i].setBackground(Color.white);
                button[i].setFont(new Font("黑体", Font.BOLD, 20));
            }
            if (i == 19) button[i].setFont(new Font(Font.SERIF, Font.PLAIN, 18));
            button[i].setForeground(Color.black);

            button[i].setBorderPainted(false); 
        }
        button[27].setBackground(color2);  

        keysPanel.setBackground(color1);

        frame.getContentPane().add("North", processTextPanel);
        frame.getContentPane().add("Center", resultTextPanel);
        frame.getContentPane().add("South", keysPanel);
        processTextPanel.setBorder(BorderFactory.createMatteBorder(25, 3, 0, 3, color1));
        resultTextPanel.setBorder(BorderFactory.createMatteBorder(0, 3, 5, 3, color1));
        keysPanel.setBorder(BorderFactory.createMatteBorder(5, 3, 5, 3, color1));

        for (int i = 0; i < keys.length; i++) {
            button[i].addActionListener(this);
        }
    }

    public void actionPerformed(ActionEvent ev) {

        String command = ev.getActionCommand(); 

        if (command.equals(keys[3])) doBackspace();
        else if (command.equals(keys[1])) resultText.setText("0");
        else if (command.equals(keys[2])) doC();
        else if ("0123456789.".indexOf(command) >= 0) doNumber(command);
        else if (command.equals(keys[0]) || command.equals(keys[4]) || command.equals(keys[6])
                || command.equals(keys[7]) || command.equals(keys[8]) || command.equals(keys[9])
                || command.equals(keys[10]) || command.equals(keys[24])) doOperator1(command);
        else doOperator2(command);
    }


    private void doBackspace() {
        String text = resultText.getText();
        int i = text.length();
        if (i > 0) {
            text = text.substring(0, i - 1); 
            if (text.length() == 0) {
                resultText.setText("0");
                firstDigit = true;
                operator = "=";
            } else {
                resultText.setText(text);
            }
        }
    }

    private void doC() {
        processText.setText(null);
        resultText.setText("0");
        firstDigit = true;
        operator = "=";
    }

    private void doNumber(String key) {
        if (firstDigit) {
            resultText.setText(null);
            resultText.setText(key);

        } else if ((key.equals(".")) && (resultText.getText().indexOf(".") < 0)) {
            resultText.setText(resultText.getText() + ".");
        } else if (!key.equals(".")) { 
            resultText.setText(resultText.getText() + key);
        }
        firstDigit = false;
    }


    private void doOperator1(String key) {
        operator = key;  
        if (operator.equals("1⁄x")) {
            if (resultNum == 0) {
                operateValidFlag = false; 
                resultText.setText("除数不能为零");
            } else {
                resultNum = 1 / getNumberFromText();
                processText.setText("1/(" + resultText.getText() + ")");
            }
        } else if (operator.equals("√x")) {
            if (resultNum < 0) {
                operateValidFlag = false;  
                resultText.setText("无效输入");
            } else {
                resultNum = Math.sqrt(getNumberFromText());
                processText.setText("√(" + resultText.getText() + ")");
            }
        } else if (operator.equals("x²")) {
            resultNum = getNumberFromText() * getNumberFromText();
            processText.setText("sqr(" + resultText.getText() + ")");
        } else if (operator.equals("%")) {
            resultNum = getNumberFromText() / 100;
        } else if (operator.equals("n!")) {
        	 if (getNumberFromText() < -1) {
                 operateValidFlag = false; 
                 resultText.setText("无效输入");
             } else {
            	 BigInteger num = new BigInteger("1");
                 BigInteger flat = new BigInteger("1");
                 for (int i = 0; i < getNumberFromText(); i++) {
                     flat = flat.multiply(num);
                     num = num.add(new BigInteger("1"));
                 }
                 resultNum = flat.floatValue();//BigInteger转换为float
                 processText.setText("fact(" + resultText.getText() + ")");
             }
            
        } else if (operator.equals("cos")) {
            resultNum = Math.cos(getNumberFromText());
            processText.setText("cos(" + resultText.getText() + ")");
        } else if (operator.equals("sin")) {
            resultNum = Math.sin(getNumberFromText());
            processText.setText("sin(" + resultText.getText() + ")");
        } else if (operator.equals("+/-")) {
            resultNum = getNumberFromText() * (-1);
        }
        isOperateValidFlag(operateValidFlag);
        firstDigit = true;
        if (operateValidFlag == false) processText.setText(null);
        operateValidFlag = true;
    }


    private void doOperator2(String key) {
        if (operator.equals("÷")) {
            if (getNumberFromText() == 0.0) {
                operateValidFlag = false; 
                resultText.setText("除数不能为零");
            } else {
                resultNum /= getNumberFromText();
            }
        } else if (operator.equals("+")) {
            resultNum += getNumberFromText();
        } else if (operator.equals("－")) {
            resultNum -= getNumberFromText();
        } else if (operator.equals("×")) {
            resultNum *= getNumberFromText();
        } else if (operator.equals("=")) {
            resultNum = getNumberFromText();
            processText.setText(null);
        } else if (operator.equals("aⁿ")) {
            resultNum = Math.pow(resultNum, getNumberFromText());
        }

        if (key.equals("+") || key.equals("×") || key.equals("÷") || key.equals("=")) {
            processText.setText(processText.getText() + resultText.getText() + key);
        } else if (key.equals("－")) {
            processText.setText(processText.getText() + resultText.getText() + "-");
        } else if (key.equals("aⁿ")) {
            processText.setText(processText.getText() + resultText.getText() + "^");

        }

        isOperateValidFlag(operateValidFlag);
        operator = key;
        firstDigit = true;
        if (operateValidFlag == false) {
            processText.setText(null);
        }
        operateValidFlag = true;
    }

    private void isOperateValidFlag(boolean operateValidFlag) {
        if (operateValidFlag) {
            long t1 = (long) resultNum;
            double t2 = resultNum - t1;
            BigDecimal bd = new BigDecimal(String.valueOf(resultNum));
            if (t2 == 0) {
                resultText.setText(String.valueOf(t1));
            } else if (bd.scale() == 1) {
                resultText.setText(String.valueOf(new DecimalFormat("0.0").format(resultNum)));
            } else if (bd.scale() == 2) {
                resultText.setText(String.valueOf(new DecimalFormat("0.00").format(resultNum)));
            } else if (bd.scale() == 3) {
                resultText.setText(String.valueOf(new DecimalFormat("0.000").format(resultNum)));
            } else if (bd.scale() == 4) {
                resultText.setText(String.valueOf(new DecimalFormat("0.0000").format(resultNum)));
            } else if (bd.scale() == 5) {
                resultText.setText(String.valueOf(new DecimalFormat("0.00000").format(resultNum)));
            } else if (bd.scale() == 6) {
                resultText.setText(String.valueOf(new DecimalFormat("0.000000").format(resultNum)));
            } else if (bd.scale() == 7) {
                resultText.setText(String.valueOf(new DecimalFormat("0.0000000").format(resultNum)));
            } else if (bd.scale() == 8) {
                resultText.setText(String.valueOf(new DecimalFormat("0.00000000").format(resultNum)));
            } else {
                resultText.setText(String.valueOf(new DecimalFormat("0.000000000").format(resultNum)));
            }
        }
    }

    private double getNumberFromText() {
        double result = 0;
        try {
            result = Double.valueOf(resultText.getText()).doubleValue();
        } catch (NumberFormatException e) {
        }
        return result;
    }

    public static void main(String[] args) {
        new Calculator();
    }
}